<script setup lang="ts">
import { watch, ref, defineEmits, reactive } from "vue";
import { usetaskPass, taskTableDetiall } from "@/store/modules/taskPass";
import { FormInstance } from "element-plus";
const ChangeHeader = ref<any>([]);
const SavePanelVisible = ref<boolean>(false);
const updatePanelVisible = ref<boolean>(false);
const fromtips = ref<FormInstance>();
const [usetaskPass_, taskDetiall_] = [usetaskPass(), taskTableDetiall()];
const SingleOption = reactive({});
const isChangeDisabled = ref(false)
const shouldUpdate = ref(0)
const form = ref({
  taskKeywordId: 0,
  examinationPaperId: "0",
  planId: 0,
  taskId: 0,
  taskDetailId: 0,
});

function handleTrim(i) {
  form.value['value' + Number(i + 1)] = form.value['value' + Number(i + 1)].replace(/\s/g, '')
}

function handleTrimEdit(i) {
  forms.value['value' + Number(i + 1)] = forms.value['value' + Number(i + 1)].replace(/\s/g, '')
}

const getValue = (index) => {
  // console.log('我记拿来了', index);

  const key = 'value' + (index + 1);
  if (!form.value.hasOwnProperty(key)) {
    form.value[key] = { start: 0, end: 0 };
  }
  return form.value[key];
};

const updateValue = (index, prop, value) => {
  const key = 'value' + (index + 1);
  console.log(value);

  form.value[key][prop] = parseFloat(value);
};

const getValue1 = (index) => {
  const key = 'value' + (index + 1);
  if (!forms.value.hasOwnProperty(key)) {
    forms.value[key] = { start: 0, end: 0 };
  }
  return forms.value[key];
};

const updateValue1 = (index, prop, value) => {
  const key = 'value' + (index + 1);
  forms.value[key][prop] = parseFloat(value);
};

const forms = ref({});
const emits = defineEmits(["ClosePanelVisible", "updateSetForm"]);
const props = defineProps({
  SavePanelVisible: {
    type: Boolean
  },
  updatePanelVisible: {
    type: Boolean
  },
  headers: {
    type: Array
  },
  setForm: {
    type: Object
  }
});
watch(
  props,
  newval => {
    // console.log('见来了watch');

    ChangeHeader.value = newval.headers;
    forms.value = newval.setForm;
    //处理区间值 拿到一个value  例如6，7 那边页面dom渲染进行计算属性赋值
    for (const key in forms.value) {
      if (/^value\d+$/.test(key)) {
        if (typeof forms.value[key] === "string" && forms.value[key] !== "") {
          // console.log(forms.value[key]);
          const values = forms.value[key].split(",");
          const regex = /^-?\d+(\.\d+)?$/;
          if (values.length === 2 && regex.test(values[0]) && regex.test(values[1])) {
            forms.value[key] = {
              start: parseFloat(values[0]),
              end: parseFloat(values[1])
            };
            break;
          }
        }
      }
    }//修改关键字-内容
    SavePanelVisible.value = newval.SavePanelVisible; // 添加关键字
    updatePanelVisible.value = newval.updatePanelVisible; // 修改关键字
    if (newval.headers.length !== 0) {
      DropDownSelection(newval.headers);
    }
  },
  { deep: true, immediate: true }
);

function handleLinkage(item) {
  //先处理联动禁止（如结算方式和融资金额）
  if (item.selectItemId == '8593') {
    form.value['value3'] = ''
    if (updatePanelVisible.value) {
      forms.value['value3'] = ''
    }
    isChangeDisabled.value = true
  } else {
    isChangeDisabled.value = false
  }

  // form.value['multistageChangeKeywordId'] = '';
  // form.value['multistageChangeKeywordType'] = '';
  if (item.childKeywordId && item.childSelectContent) {
    shouldUpdate.value = shouldUpdate.value + 1
    emits("updateSetForm", item);
  }
  //更换类型
  // } else {
  //   const keywordIdArr = item.childKeywordId.split(',');
  //   keywordIdArr.forEach(a => {
  //     const index = ChangeHeader.value.submoduleKeywordEntityResultDtos.findIndex(b => b.keywordId == a);
  //     if (item.childKeywordType == 11) {
  //       form.value['value' + (index + 1)] = {}
  //     } else {
  //       form.value['value' + (index + 1)] = null
  //     }
  //   })
  //   form.value['multistageChangeKeywordId'] = item.childKeywordId
  //   form.value['multistageChangeKeywordType'] = item.childKeywordType
  // }
}
// 保存新添加内容
function SaveFromType(row: FormInstance | undefined) {
  // console.log(taskDetiall_.data);

  (row as any).validate(async valid => {
    if (!valid) return;
    const task = usetaskPass_.data;
    const subData = reactive({
      taskId: task.taskId,
      uid: Date.now(),
      taskKeywordId: "0",
      taskDetailId: 1
    });
    for (const key in form.value) {
      if (form.value.hasOwnProperty(key) && typeof form.value[key] === "object" && form.value[key].hasOwnProperty("start") && form.value[key].hasOwnProperty("end")) {
        form.value[key] = `${form.value[key].start},${form.value[key].end}`;
      }
    }
    const from_ = {
      ...form.value,
      ...subData
    };
    taskDetiall_.data.push(from_);
    // console.log(taskDetiall_.data);

    emits("ClosePanelVisible");
    row.resetFields();
  });
}

// 保存修改的内容
function UpdateFromType(row: FormInstance | undefined) {
  (row as any).validate(async valid => {
    if (!valid) return;
    for (const key in forms.value) {
      if (forms.value[key] !== null) {
        if (forms.value.hasOwnProperty(key) && typeof forms.value[key] === "object" && forms.value[key].hasOwnProperty("start") && forms.value[key].hasOwnProperty("end")) {
          forms.value[key] = `${forms.value[key].start},${forms.value[key].end}`;
        }
      }
    }
    taskDetiall_.UPDATE_DATA(forms.value);
    emits("ClosePanelVisible");
    row.resetFields();
  });
}

// 下拉框选项
function DropDownSelection(data: any) {
  // console.log('DropDownSelection', data)
  data.submoduleKeywordEntityResultDtos.forEach((e, i) => {
    if ((e.keywordType === 2 || e.keywordType === 7) && e.selectItemDtos.length)
      SingleOption["key" + i] = e.selectItemDtos;
    else SingleOption["key" + i] = [];
  });
}

// 关闭弹窗
function ClosePanelVisible(row: FormInstance | undefined) {
  emits("ClosePanelVisible");
  row.resetFields();
  setTimeout(() => {
    form.value = {
      taskKeywordId: 0,
      examinationPaperId: "0",
      planId: 0,
      taskId: 0,
      taskDetailId: 0
    }
  }, 500)
}
</script>
<!--
  type
  -- 1 普通文本
  -- 2 下拉-单选
  -- 3 金额框
  -- 4 数字框
  -- 5 下拉加载
  -- 6 年-月-日
  -- 7 下拉-多选
  -- 8 日期年月
  -- 9 多行文本框
  -- 10
  -- 11 区间值
 -->
<template>
  <div class="comp__From">
    <el-dialog @close="ClosePanelVisible(fromtips)" v-model="SavePanelVisible" :close-on-click-modal="false"
      destroy-on-close title="添加" width="40%" center style="min-width: 550px">
      <el-scrollbar height="250px">
        <el-form label-width="155px" :model="form" ref="fromtips" size="small">
          <template v-for="(item, i) in ChangeHeader.submoduleKeywordEntityResultDtos" :key="item.keywordId">
            <!--输入文本-->
            <el-form-item v-if="item.keywordType === 1" :label="item.keywordType === 1 ? item.keywordName : ''"
              :prop="['value' + Number(i + 1)]" :rules="[{ required: true, message: '不能为空！' }]">
              <el-input type="text" v-model.trim="form['value' + Number(i + 1)]" class="!w-[220px]" />
              <div v-if="item.keywordId == 'G123'" style="color: red;">融资业务中的多个采购项目要用英文,隔开</div>
            </el-form-item>
            <!--下拉单选-->
            <el-form-item v-if="item.keywordType === 2" :key="shouldUpdate"
              :label="item.keywordType === 2 ? item.keywordName : ''" :prop="['value' + Number(i + 1)]"
              :rules="[{ required: true, message: '请选择内容！' }]">
              <el-select placeholder="单选" v-model="form['value' + Number(i + 1)]" collapse-tags collapse-tags-tooltip
                class="!w-[220px]">
                <el-option v-for="item in SingleOption['key' + Number(i)]" :key="item.selectItemId"
                  :label="item.selectName" :value="item.selectName" @click="handleLinkage(item)" />
              </el-select>
            </el-form-item>
            <!-- 金额 数字 -->
            <el-form-item v-if="item.keywordType === 3" :label="item.keywordType === 3 ? item.keywordName : ''"
              :prop="['value' + Number(i + 1)]" :rules="[{ required: true, message: '内容不能为空！' }]">
              <el-input-number v-model="form['value' + Number(i + 1)]" class="!w-[220px] el-input-number"
                controls-position="right" onmousewheel="return false;" />
              <!-- <el-input type="number" v-model.number="form['value' + Number(i + 1)]"  /> -->
            </el-form-item>
            <!--金额数字-->
            <el-form-item v-if="item.keywordType === 4" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 4 ? item.keywordName : ''" :rules="[{ required: true, message: '内容不能为空！' }]">
              <!-- <el-input type="number" v-model.number="form['value' + Number(i + 1)]" class="!w-[220px]"
                                                    :disabled="isChangeDisabled" /> -->
              <el-input-number v-model="form['value' + Number(i + 1)]" class="!w-[220px] el-input-number"
                controls-position="right" :disabled="isChangeDisabled" onmousewheel="return false;" />
            </el-form-item>
            <!--下拉多选-->
            <el-form-item v-if="item.keywordType === 7" :prop="['MultipleSelectValue' + item.keywordId]"
              :label="item.keywordType === 7 ? item.keywordName : ''"
              :rules="[{ required: true, message: '请选择内容！', type: 'any' }]" collapse-tags collapse-tags-tooltip>
              <el-select multiple placeholder="多选" v-model="form['MultipleSelectValue' + item.keywordId]"
                class="!w-[220px]">
                <!-- v-model="form['value' + Number(i + 1)]" -->
                <el-option v-for="item in SingleOption['key' + Number(i)]" :key="item.selectItemId"
                  :label="item.selectName" :value="item.selectName" />
              </el-select>
            </el-form-item>
            <!--日期+时间---->
            <el-form-item v-if="item.keywordType === 6" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 6 ? item.keywordName : ''" :rules="[{ required: true, message: '请选择时间日期' }]">
              <el-date-picker type="datetime" v-model="form['value' + Number(i + 1)]" placeholder="请选择时间日期"
                class="!w-[220px]" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <!-- 日期 -->
            <el-form-item v-if="item.keywordType === 8" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 8 ? item.keywordName : ''" :rules="[{ required: true, message: '请选择时间日期' }]">
              <el-date-picker placeholder="请选择时间" type="date" v-model="form['value' + Number(i + 1)]" class="!w-[220px]"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <!-- 文本框 -->
            <el-form-item v-if="item.keywordType === 9" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 9 ? item.keywordName : ''" :rules="[{ required: true, message: '内容不能为空！' }]">
              <el-input type="textarea" class="!w-[350px]" v-model.trim="form['value' + Number(i + 1)]"
                @input="handleTrim(i)" :rows="6" />
            </el-form-item>
            <!--区间值-->
            <el-form-item v-if="item.keywordType === 11" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 11 ? item.keywordName : ''" :rules="[{ required: true, message: '请输入区间值' }]">
              <el-col :span="4">
                <el-input type="number" v-model="getValue(i).start" @blur="updateValue(i, 'start', getValue(i).start)"
                  class="!w-[100px]" />
              </el-col>
              <el-col :span="1" class="text-center">
                <span class="text-gray-500">-</span>
              </el-col>
              <el-col :span="4">
                <el-input type="number" v-model="getValue(i).end" @blur="updateValue(i, 'end', getValue(i).end)"
                  class="!w-[100px]" />
              </el-col>
            </el-form-item>
          </template>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="SaveFromType(fromtips)">
            保存
          </el-button>
          <el-button @click="ClosePanelVisible(fromtips)">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog @close="ClosePanelVisible(fromtips)" v-model="updatePanelVisible" :close-on-click-modal="false"
      destroy-on-close title="修改" width="28%" style="min-width: 550px" center>
      <el-scrollbar height="250px">
        <el-form label-width="155px" :model="forms" ref="fromtips" size="small">
          <template v-for="(item, i) in ChangeHeader.submoduleKeywordEntityResultDtos" :key="item.keywordId">
            <!--输入文本-->
            <el-form-item v-if="item.keywordType === 1" :label="item.keywordType === 1 ? item.keywordName : ''"
              :prop="['value' + Number(i + 1)]" :rules="[{ required: true, message: '不能为空！' }]">
              <el-input type="text" v-model.trim="forms['value' + Number(i + 1)]" class="!w-[220px]" />
              <div v-if="item.keywordId == 'G123'" style="color: red;">融资业务中的多个采购项目要用英文,隔开</div>
            </el-form-item>
            <!--下拉单选-->
            <el-form-item v-if="item.keywordType === 2" :label="item.keywordType === 2 ? item.keywordName : ''"
              :prop="['value' + Number(i + 1)]" :rules="[{ required: true, message: '请选择内容！' }]" :key="shouldUpdate">
              <el-select placeholder="单选" v-model="forms['value' + Number(i + 1)]" class="!w-[220px]">
                <el-option v-for="item in SingleOption['key' + Number(i)]" :key="item.selectItemId"
                  :label="item.selectName" :value="item.selectName" @click="handleLinkage(item)" />
              </el-select>
            </el-form-item>
            <!-- 金额 数字 -->
            <el-form-item v-if="item.keywordType === 3" :label="item.keywordType === 3 ? item.keywordName : ''"
              :prop="['value' + Number(i + 1)]" :rules="[{ required: true, message: '内容不能为空！' }]">
              <el-input-number v-model="forms['value' + Number(i + 1)]" class="!w-[220px] el-input-number"
                controls-position="right" onmousewheel="return false;" />
              <!-- <el-input type="number" v-model.number="forms['value' + Number(i + 1)]" class="!w-[220px]" /> -->
            </el-form-item>
            <!--金额数字-->
            <el-form-item v-if="item.keywordType === 4" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 4 ? item.keywordName : ''" :rules="[{ required: true, message: '内容不能为空！' }]">
              <el-input-number v-model="forms['value' + Number(i + 1)]" class="!w-[220px] el-input-number"
                controls-position="right" :disabled="isChangeDisabled" onmousewheel="return false;" />
              <!-- <el-input type="number" v-model.number="forms['value' + Number(i + 1)]" class="!w-[220px]"
                              :disabled="isChangeDisabled" /> -->
            </el-form-item>
            <!--下拉多选-->
            <el-form-item v-if="item.keywordType === 7" :prop="['MultipleSelectValue' + item.keywordId]"
              :label="item.keywordType === 7 ? item.keywordName : ''"
              :rules="[{ required: true, message: '请选择内容！', type: 'any' }]">
              <el-select multiple placeholder="多选" v-model="forms['MultipleSelectValue' + item.keywordId]" collapse-tags
                collapse-tags-tooltip class="!w-[220px]">
                <el-option v-for="item in SingleOption['key' + Number(i)]" :key="item.selectItemId"
                  :label="item.selectName" :value="item.selectName" />
              </el-select>
            </el-form-item>
            <!--日期+时间-->
            <el-form-item v-if="item.keywordType === 6" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 6 ? item.keywordName : ''" :rules="[{ required: true, message: '请选择时间日期' }]">
              <el-date-picker type="datetime" v-model="forms['value' + Number(i + 1)]" placeholder="请选择时间日期"
                class="!w-[220px]" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <!--日期-->
            <el-form-item v-if="item.keywordType === 8" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 8 ? item.keywordName : ''" :rules="[{ required: true, message: '请选择时间！' }]">
              <el-date-picker placeholder="请选择时间" type="date" v-model="forms['value' + Number(i + 1)]" class="!w-[220px]"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <!--多行文本框-->
            <el-form-item v-if="item.keywordType === 9" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 9 ? item.keywordName : ''" :rules="[{ required: true, message: '内容不能为空！' }]">
              <el-input type="textarea" class="!w-[350px]" v-model.trim="forms['value' + Number(i + 1)]"
                @input="handleTrimEdit(i)" :rows="6" />
            </el-form-item>
            <!--区间值-->
            <el-form-item v-if="item.keywordType === 11" :prop="['value' + Number(i + 1)]"
              :label="item.keywordType === 11 ? item.keywordName : ''" :rules="[{ required: true, message: '请输入区间值' }]">
              <el-col :span="7">
                <el-input type="number" v-model="getValue1(i).start" @blur="updateValue1(i, 'start', getValue1(i).start)"
                  class="!w-[100px]" />
              </el-col>
              <el-col :span="1" class="text-center">
                <span class="text-gray-500">-</span>
              </el-col>
              <el-col :span="7">
                <el-input type="number" v-model="getValue1(i).end" @blur="updateValue1(i, 'end', getValue1(i).end)"
                  class="!w-[100px]" />
              </el-col>
            </el-form-item>
          </template>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="UpdateFromType(fromtips)">
            保存
          </el-button>
          <el-button @click="ClosePanelVisible(fromtips)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.comp__From {
  .el-form-item {
    margin-bottom: 20px;
  }
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 7px !important;
}
</style>
